#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author : sixther.me
#date : 2014-10-11

import os
import sys
import MySQLdb


DBHost='172.16.1.196'
DBName='zabbix'
DBUser='zabbix'
DBPassword='xxxxxxxxxxxxx'

item_list={'eth0-in':'Traffic for eth0 Receive','eth0-out':'Traffic for eth0 Send','eth1-in':'Traffic for eth1 Receive','eth1-out':'Traffic for eth1 Send'}

rack=sys.argv[1]
item=item_list[sys.argv[2]]

zabbix_conn=MySQLdb.connect(host='172.16.1.196',user='zabbix',passwd='NgLspIuF4Oc1d0GGDNV1',db='zabbix',charset='utf8')

def fetch_list_sql(sql):
	zabbix_cursor=zabbix_conn.cursor()
        zabbix_cursor.execute(sql)
	result=zabbix_cursor.fetchall()
#        result='%s' % zabbix_cursor.fetchone()
#	zabbix_conn.commit()
        zabbix_cursor.close()
        return result

def fetch_one_sql(sql): 
	zabbix_cursor=zabbix_conn.cursor()
	zabbix_cursor.execute(sql)
	result='%s' % zabbix_cursor.fetchone()
	zabbix_cursor.close()
	return result

if __name__ == '__main__':
	traffic_sum=0
	query_item_list_sql="select items.itemid from items,server_inventory where server_inventory.hostid=items.hostid and server_inventory.rack='" + rack + "' and items.name='" + item + "'"
	if sys.argv[1] == 'all':
		query_item_list_sql="select items.itemid from items,hosts_groups where hosts_groups.hostid=items.hostid and hosts_groups.groupid=12  and items.name='" + item + "'"
	item_list=fetch_list_sql(query_item_list_sql)
	for i in item_list:
		query_value_sql="select value from history where itemid= " + str(i[0]) + " order by clock desc limit 1"
		i_value=fetch_one_sql(query_value_sql)
		traffic_sum=traffic_sum + float(i_value)
	print traffic_sum

